/*
Author : Nguyen Van Ty
Email  : ngvanty03@gmail.com
Date   : 12/27/2010 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using BusinessObject;
using Utility;
using System.Xml;
namespace DataAccessLayer
{
    /// <summary>
    /// Define KhachHangDaoBase class. This class user for DataAccessLayer, contain 4 function Insert, Update, Search, Delete.
    /// If you want add new function, you must define in KhachHangDao class , not here.
    /// </summary>
    public class KhachHangDaoBase
    {
        private static ILog logger = null;
        #region Constructor
        /// <summary>
        /// Define Constructor.
        /// </summary>
        public KhachHangDaoBase() { }
        static KhachHangDaoBase()
        {
            //Init logger.
            logger = LoggingUtility.GetLogger(typeof(KhachHangDaoBase).FullName);
        }
        #endregion
        /// <summary>
        /// Read data from IDataReader, convert to KhachHang Object.
        /// </summary>
        private static KhachHang GetKhachHangByDataReader(IDataReader reader)
        {
            String methodName = "GetKhachHangByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                KhachHang result = new KhachHang();
                //read MaKhachHang field data.

                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read TenKhachHang field data.

                result.TenKhachHang = ManagerDao.GetstringDataFromDataReader(reader, "TenKhachHang");

                //read DiaChi field data.

                result.DiaChi = ManagerDao.GetstringDataFromDataReader(reader, "DiaChi");

                //read DienThoai field data.

                result.DienThoai = ManagerDao.GetstringDataFromDataReader(reader, "DienThoai");

                //read Email field data.

                result.Email = ManagerDao.GetstringDataFromDataReader(reader, "Email");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Define function Insert for KhachHang Object.
        /// </summary>
        /// <param name="obj">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static int Insert(KhachHang obj)
        {
            int result = 0;
            String methodName = "InsertKhachHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertKhachHang");

            //Add value "TenKhachHang"  paramater.
            ManagerDao.AddInParameter(cmd, "TenKhachHang", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.TenKhachHang));
            //Add value "DiaChi"  paramater.
            ManagerDao.AddInParameter(cmd, "DiaChi", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.DiaChi));
            //Add value "DienThoai"  paramater.
            ManagerDao.AddInParameter(cmd, "DienThoai", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.DienThoai));
            //Add value "Email"  paramater.
            ManagerDao.AddInParameter(cmd, "Email", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.Email));
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                result = Int32.Parse(ManagerDao.GetParameterValue(cmd, "returnValue").ToString());

            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);

            }
            return result;
        }

        /// <summary>
        /// Define function Update for KhachHang Object.
        /// </summary>
        /// <param name="obj">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static bool Update(KhachHang obj)
        {
            bool result = false;
            String methodName = "UpdateKhachHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdateKhachHang");


            //Add value "MaKhachHang"  paramater.
            ManagerDao.AddInParameter(cmd, "MaKhachHang", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.MaKhachHang));
            //Add value "TenKhachHang"  paramater.
            ManagerDao.AddInParameter(cmd, "TenKhachHang", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.TenKhachHang));
            //Add value "DiaChi"  paramater.
            ManagerDao.AddInParameter(cmd, "DiaChi", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.DiaChi));
            //Add value "DienThoai"  paramater.
            ManagerDao.AddInParameter(cmd, "DienThoai", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.DienThoai));
            //Add value "Email"  paramater.
            ManagerDao.AddInParameter(cmd, "Email", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.Email));
            // add parameter store return value.
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                int rows = (int)ManagerDao.GetParameterValue(cmd, "returnValue");
                if (rows == 1)//Successfull.
                {
                    result = true;
                }
                else//Error.
                {
                    result = false;
                }

            }
            catch (Exception e)
            {
                //write error Message to log file.
                logger.Error(methodName, e);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// Get Data KhachHang object. 
        /// </summary>
        /// <param name="maKhachHang" >This is primary key to get data.</param>
        /// <returns>KhachHang object.</returns>

        public static KhachHang Get(int maKhachHang)
        {
            String methodName = "GetKhachHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                KhachHang result = null;
                DbCommand dbCommnand = ManagerDao.GetStoredProcCommand("spGetKhachHang");
                //Add value "MaKhachHang"  paramater.
                ManagerDao.AddInParameter(dbCommnand, "MaKhachHang", DbType.Int32, maKhachHang);
                IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
                if (reader.Read())
                {
                    result = GetKhachHangByDataReader(reader);

                }
                reader.Close();
                return result;
            }
            catch (System.Exception e)
            {
                //write error message to log file.
                logger.Error("Get", e);
                return null;
            }
        }
        /// <summary>
        /// Get All KhachHang object from table KhachHang.
        /// </summary>
        /// <returns>List KhachHang object.</returns>
        public static List<KhachHangResult> GetAll()
        {
            String methodName = "GetAll";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<KhachHangResult> listKhachHang = new List<KhachHangResult>();
                DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spGetAllKhachHang");

                using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
                {
                    while (reader.Read())
                    {
                        listKhachHang.Add(GetKhachHangResultByDataReader(reader));
                    }
                    reader.Close();
                }

                return listKhachHang;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }

        /// <summary>
        /// Search KhachHang object in table KhachHang with condition is t object.
        /// </summary>
        /// <param name="t">Condition for Search.</param>       
        /// <param name="totalRow">  total records in this table.</param>
        /// <returns>List KhachHangResult object.</returns>
        public static List<KhachHangResult> SearchKhachHangSomeCondition(KhachHang t)
        {
            String methodName = "SearchKhachHangSomeCondition";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<KhachHangResult> listKhachHang = new List<KhachHangResult>();
                DbCommand cmd = ManagerDao.GetStoredProcCommand("spSearchKhachHangByCondition");
                //Add value Condition  paramater.
                ManagerDao.AddInParameter(cmd, "Condition", DbType.String, ConvertValueObject.CastObjValueToInsertDB(t.Condition));

                //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, "PageIndex", DbType.Int32, t.ObjectPaging.PageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, "PageSize", DbType.Int32, t.ObjectPaging.PageSize);
                //Add value SortField  paramater.
                ManagerDao.AddInParameter(cmd, "SortField", DbType.String, t.ObjectSortOrder.SortField);
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd, "SortExpression", DbType.String, t.ObjectSortOrder.SortExpression);
                using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
                {
                    while (reader.Read())
                    {
                        listKhachHang.Add(GetKhachHangResultByDataReader(reader));
                        if (t.ToltalRow <= 0)
                            t.ToltalRow = ManagerDao.Getint32DataFromDataReader(reader, "TotalRow");
                    }

                    reader.Close();
                }

                return listKhachHang;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }
        /// <summary>
        /// Delete KhachHang object. 
        /// </summary>
        /// <param name="MaKhachHang" >This is primary key to delete.</param>
        /// <returns>True/False.</returns>

        public static bool Delete(int MaKhachHang)
        {
            String methodName = "DeleteKhachHang";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spDeleteKhachHang");
                //Add value "MaKhachHang"  paramater.
                ManagerDao.AddInParameter(dbCommand, "MaKhachHang", DbType.Int32, MaKhachHang);
                //Add value returnValue  paramater.
                ManagerDao.AddParameter(dbCommand, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
                try
                {
                    ManagerDao.ExecuteNonQuery(dbCommand);
                    int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, "returnValue");
                    if (parameterValue == 1)
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return false;
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
                return false;
            }
        }
        /// <summary>
        /// Read data from IDataReader, convert to KhachHangResult Object.
        /// </summary>
        private static KhachHangResult GetKhachHangResultByDataReaderByLanguage(IDataReader reader, string LanguageId)
        {
            String methodName = "GetKhachHangResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                KhachHangResult result = new KhachHangResult();
                //read MaKhachHang field data.
                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read TenKhachHang field data.
                result.TenKhachHang = ManagerDao.GetstringDataFromDataReader(reader, "TenKhachHang");

                //read DiaChi field data.
                result.DiaChi = ManagerDao.GetstringDataFromDataReader(reader, "DiaChi");

                //read DienThoai field data.
                result.DienThoai = ManagerDao.GetstringDataFromDataReader(reader, "DienThoai");

                //read Email field data.
                result.Email = ManagerDao.GetstringDataFromDataReader(reader, "Email");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Read data from IDataReader, convert to KhachHangResult Object.
        /// </summary>
        private static KhachHangResult GetKhachHangResultByDataReader(IDataReader reader)
        {
            String methodName = "GetKhachHangResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                KhachHangResult result = new KhachHangResult();
                //read MaKhachHang field data.
                result.MaKhachHang = ManagerDao.GetintDataFromDataReader(reader, "MaKhachHang");

                //read TenKhachHang field data.
                result.TenKhachHang = ManagerDao.GetstringDataFromDataReader(reader, "TenKhachHang");

                //read DiaChi field data.
                result.DiaChi = ManagerDao.GetstringDataFromDataReader(reader, "DiaChi");

                //read DienThoai field data.
                result.DienThoai = ManagerDao.GetstringDataFromDataReader(reader, "DienThoai");

                //read Email field data.
                result.Email = ManagerDao.GetstringDataFromDataReader(reader, "Email");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }

    }
}